package procsim;

public class BigDecoder implements Element{
    private MSignal inSig;
    private BigMSignal result;
    private Signal enable = new Signal(1);
    protected int inNum, outNum;
    protected boolean enableNotSet = true;
    protected String name = "DC";
    public BigDecoder(int num){
        inNum=num;
        outNum=(int)Math.pow(2, inNum); // broj izlaznih signala je 2^(inNum)
        result=new BigMSignal(outNum, 0);
    }
    public BigDecoder(int number, MSignal in){
        this(number);
        if(in!=null) in.addElement(this);
        inSig=in;
    }
    public BigDecoder setResult(BigMSignal sig){
        result=sig;
        return this;
    }
    public BigDecoder setEnableBit(Signal sig){
        if(sig!=null) sig.addElement(this);
        enable = sig;
        enableNotSet = false;
        return this;
    }
    public void setName(String name){
        this.name = name;
    }
    @Override
    public BigDecoder tick(){
        if(result==null) return this;
        if(inSig==null || (enable!=null && enable.isNull())){
            for(int i=0; i<result.getNumOfBits(); i++) result.set(i, 0);
            return this;
        }
        int index=inSig.get();
        for(int i=0; i<result.getNumOfBits(); i++){
            if(i==index) result.set(i, 1);
            else result.set(i, 0);
        }
        return this;
    }
    @Override
    public BigMSignal result(){
        return result;
    }
    @Override
    public String toString(){
        return ""+result;
    }
    @Override
    public void updateSignal(Sig sig) {
        boolean changed = false;
        if(inSig!=null && inSig==sig){
            inSig.set(sig.get(), false);
            changed = true;
        }
        if(enable!=null && enable==sig){
            enable.set(sig.get(), false);
            changed = true;
        }
        if(changed) tick();
    }
    
}
